#include "ExplosionManager.h"
#include "EntityExplosion.h"
#include "WorldModel.h"
#include <assert.h>

CExplosionManager* CExplosionManager::instance=NULL;

CExplosionManager::CExplosionManager(void):indexFirstExplosion(-1), indexLastExplosion(-1)
{}

CExplosionManager::~CExplosionManager(void)
{
	for(vector<CEntityExplosion*>::iterator p=vectorExplosionTemplate.begin(); p<vectorExplosionTemplate.end(); p++)
	{
		delete (*p);
		(*p)=NULL;
	}
}

CExplosionManager& CExplosionManager::getInstance(void)
{
	if(instance==NULL)
	{
		instance=new CExplosionManager();
	}
	return *instance;
}

/*function that close and delete the explosion manager*/
void CExplosionManager::Close(void)
{
	delete CExplosionManager::instance;
	CExplosionManager::instance=NULL;
}

/*create a template of explosion*/
void CExplosionManager::createExplosionTemplate(int indexAnimation, int offsetSpawnX, int offsetSpawnY)
{
	assert(indexAnimation>=0);
	CEntityExplosion* newEntity= new CEntityExplosion(0,0, indexAnimation, offsetSpawnX, offsetSpawnY, true);
	this->vectorExplosionTemplate.push_back(newEntity);
}

/*create all the explosion in the entity vector of the world model. All the explosions are inactive*/
void CExplosionManager::createAllExplosion(int numberOfExplosion)
{
	assert(numberOfExplosion>0);

	this->indexFirstExplosion=WMODEL.getEntityVectorSize();;
	for(int i=0;i<numberOfExplosion;i++)
	{
		CWorldEntity* newEntity= new CEntityExplosion(0, 0, 0,0,0, false);
		WMODEL.addEntity(newEntity);
	}
	this->indexLastExplosion=this->indexFirstExplosion+numberOfExplosion-1;
}

/*spawn an explosion if a there is a free space*/
void CExplosionManager::spawnExplosion(CEntityExplosion* explosionTemplate, int positionX, int positionY)
{
	//look for an empty space for an explosion
	bool found=false;
	int indexExplosion=this->indexFirstExplosion;
	while(indexExplosion<=this->indexLastExplosion && found==false)
	{
		if(WMODEL.getActive(indexExplosion))
		{
			indexExplosion++;
		}
		else
		{
			found=true;
		}
	}
	//if we can spawn an explosion
	if(found==true)
	{		
		CEntityExplosion* explosion=(CEntityExplosion*)WMODEL.getEntityPnter(indexExplosion);
		(*explosion)=(*explosionTemplate);
		explosion->setCurrentPosX(positionX);
		explosion->setCurrentPosY(positionY);
	}
}

/*function that return a pointer to a explosion template*/
CEntityExplosion* CExplosionManager::getExplosionTemplate(int index)
{
	return this->vectorExplosionTemplate[index];
}
int CExplosionManager::getIndexFirstExplosion(void)const
{
	return this->indexFirstExplosion;
}
int CExplosionManager::getIndexLastExplosion(void)const
{
	return this->indexLastExplosion;
}

void CExplosionManager::setIndexFirstExplosion(int indexFirstExplosion)
{
	this->indexFirstExplosion=indexFirstExplosion;
}
void CExplosionManager::setIndexLastExplosion(int indexLastExplosion)
{
	this->indexLastExplosion=indexLastExplosion;
}